package com.bootdo.system.controller;

import com.bootdo.common.utils.ExcelExportUtil4DIY;
import com.bootdo.common.utils.Query;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 导出
 *
 *
 * @return
 * @throws Exception
 */
@RequestMapping("/sys/user")
@Controller
public class ExportExcelController {

    @Autowired
    UserService userService;
    private static final Logger logger = LoggerFactory.getLogger(ExportExcelController.class);

    @RequestMapping(value = "/exportExcel")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String filename = "用户表" + format.format(new Date().getTime()) + ".xls";
        response.setContentType("application/ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "iso-8859-1"));
        OutputStream out = response.getOutputStream();
        try {
            Query query = new Query(params);
            System.out.println("query============="+query);
            String type = request.getParameter("type");
            //导出当前页面数据
            if (type.equals("1")) {
                List<UserDO> userDo = userService.list(query);
                ExcelExportUtil4DIY.exportToFile(userDo, out);
            }
            //导出全部数据
            if (type.equals("2")) {
                List<UserDO> userDo = userService.list(null);
                ExcelExportUtil4DIY.exportToFile(userDo, out);
            }
            //导出符合条件的全部数据
            /*if (type.equals("3")) {
                query.remove("offset");
                query.remove("limit");
                List<UserDO> userDo = userService.list(query);
                ExcelExportUtil4DIY.exportToFile(userDo, out);
            }*/
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("exportExcel出错" + e.getMessage());
        } finally {
            out.close();
        }
    }
}